import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.createCoroutine
import kotlin.coroutines.resume

fun main(){

    launchFish {
        println("I am a coroutine")
    }

    runBlocking {
        val flow = MutableSharedFlow<String>(1)

        flow.emit("hello world")

        launch {
            flow.collect {
                println("collect:$it")
            }
        }
    }
}

fun <T> launchFish(block: suspend () -> T) {
    //创建协程，返回值为SafeContinuation(实现了Continuation 接口)
    //入参为Continuation 类型，参数名为completion，顾名思义就是
    //协程结束后(正常返回&抛出异常）将会调用它。
    var coroutine = block.createCoroutine(object : Continuation<T> {
        override val context: CoroutineContext
            get() = EmptyCoroutineContext

        //协程结束后调用该函数
        override fun resumeWith(result: Result<T>) {
            println("result:$result")
        }
    })
    //开启协程
    coroutine.resume(Unit)
}
